﻿
using System;
using System.Collections.Generic;
using Xss.Core;

namespace Xss.Configuration
{
    /// <summary>
    /// 配置引擎通用接口
    /// </summary>
    public interface IConfigurationEngine
    {
        /// <summary>
        /// 加载事件
        /// </summary>
        event EventHandler<LoadResourceEventArgs> Load;

        /// <summary>
        /// 加载配置信息
        /// </summary>
        /// <param name="args">需要加载的配置信息路径</param>
        IContextFactory LoadConfiguration(params string[] args);
    }

    /// <summary>
    /// 配置引擎基类
    /// </summary>
    public abstract class ConfigurationEngine : IConfigurationEngine
    {
        /// <summary>
        /// 资源加载事件,加载完成后触发
        /// </summary>
        public event EventHandler<LoadResourceEventArgs> Load;

        /// <summary>
        /// 触发加载事件
        /// </summary>
        /// <param name="resource"></param>
        void RaiseLoadEvents(string resource)
        {
            if (Load != null)
            {
                var args = new LoadResourceEventArgs { Resource = resource };
                Load.Invoke(this, args);
            }
        }

        /// <summary>
        /// 加载配置信息
        /// </summary>
        /// <param name="args"></param>
        public virtual IContextFactory LoadConfiguration(params string[] args)
        {
            Resources = new List<IO.IResource>();
            //加载所有配置资源到资源列表
            foreach (var s in args)
            {
                var r = Xss.IO.ResourceLoaderRegistry.GetResource(s);

                Resources.Add(r);
                RaiseLoadEvents(s);
            }

            Interpreter.ResolveResource(Resources.ToArray());
            return Interpreter.BuildContextFactory();
        }

        /// <summary>
        /// 配置资源列表
        /// </summary>
        protected List<Xss.IO.IResource> Resources { get; set; }


        /// <summary>
        /// 配置解析器
        /// </summary>
        public IConfigurationInterpreter Interpreter
        {
            get
            {
                if (_interpreter == null)
                    _interpreter = CreateConfigurationInterpreter();
                return _interpreter;
            }
        }

        private IConfigurationInterpreter _interpreter;

        protected abstract IConfigurationInterpreter CreateConfigurationInterpreter();
    }

}
